package imp

import (
	sqlc "bgs/db/sqlc"
	userFanGrpc "bgs/grpc/gen/service/user_fan"
	"bgs/grpc/gen/shared/message"
	"context"
	"fmt"
)

/****************************************************************************************/
/*                               user_fan entity of helper                              */
/****************************************************************************************/

func transformUserFanEntityToPb(userFan sqlc.UserFan) *userFanGrpc.UserFanEntity {
	return &userFanGrpc.UserFanEntity{
		Id:             userFan.ID,
		UserId:         userFan.UserID,
		FollowerUserId: userFan.FollowerUserID,
		BeFollowed:     sqlc.GoTimeToPBTimestamp(userFan.BeFollowed),
		AliasName:      userFan.AliasName,
		Remark:         userFan.Remark.String,
	}
}

/****************************************************************************************/
/*                               user_fan entity of cmd                                 */
/****************************************************************************************/

// UpsertUserFan 创建用户粉丝关系
func (s *UserAPIService) UpsertUserFan(ctx context.Context, req *userFanGrpc.UpsertUserFanRequest) (res *userFanGrpc.UpsertUserFanResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("user_fanImp->UpsertUserFan:%v", req)
	res = &userFanGrpc.UpsertUserFanResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	arg := sqlc.UpsertUserFanParams{
		UserID:         req.UserId,
		FollowerUserID: req.FollowerUserId,
		BeFollowed:     sqlc.PBTimestampToGoTime(req.BeFollowed),
		AliasName:      req.AliasName,
	}
	userFan, err := s.dao.Q.UpsertUserFan(ctx, arg)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.UserFan = transformUserFanEntityToPb(userFan)
	return
}

// UpdateUserFan 更新用户粉丝关系
func (s *UserAPIService) UpdateUserFan(ctx context.Context, req *userFanGrpc.UpdateUserFanRequest) (res *userFanGrpc.UpdateUserFanResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("user_fanImp->UpdateUserFan:%v", req)
	res = &userFanGrpc.UpdateUserFanResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	arg := sqlc.UpdateUserFanParams{
		ID:        req.Id,
		AliasName: req.AliasName,
		Remark:    sqlc.NSFromString(req.Remark),
	}
	userFan, err := s.dao.Q.UpdateUserFan(ctx, arg)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.UserFan = transformUserFanEntityToPb(userFan)
	return
}

/****************************************************************************************/
/*                               user_fan entity of query                               */
/****************************************************************************************/

// GetUserFan 获取单个用户粉丝
func (s *UserAPIService) GetUserFan(ctx context.Context, req *userFanGrpc.GetUserFanRequest) (res *userFanGrpc.GetUserFanResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("user_fanImp->GetUserFan:%v", req)
	res = &userFanGrpc.GetUserFanResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	userFan, err := s.dao.Q.GetUserFan(ctx, req.Id)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.UserFan = transformUserFanEntityToPb(userFan)
	return
}

/****************************************************************************************/
/*                            user_fanJoins entity of helper                            */
/****************************************************************************************/

func transformUserFanWithUserStatEntityToPb(row sqlc.ListUserFanWithUserStatsRow) *userFanGrpc.UserFanWithUserStatEntity {
	return &userFanGrpc.UserFanWithUserStatEntity{
		// user_fan
		Id:             row.ID,
		UserId:         row.UserID,
		FollowerUserId: row.FollowerUserID,
		BeFollowed:     sqlc.GoTimeToPBTimestamp(row.BeFollowed),
		AliasName:      row.AliasName,
		Remark:         row.Remark.String,
		// follower user_info
		FollowerUserNickName: row.FollowerUserNickName,
		FollowerUserPic:      row.FollowerUserPic,
		// user_stat
		FansCount:            row.FansCount,
		FollowUserCount:      row.FollowUserCount,
		FollowBrandCount:     row.FollowBrandCount,
		EndorseBrandCount:    row.EndorseBrandCount,
		EndorseActivityCount: row.EndorseActivityCount,
		InvolveActivityCount: row.InvolveActivityCount,
		OrderCount:           row.OrderCount,
		ViewCount:            row.ViewCount,
		PayAmount:            row.PayAmount,
	}
}

func mapUserFanWithUserStatEntityToPb(list []sqlc.ListUserFanWithUserStatsRow, f func(sqlc.ListUserFanWithUserStatsRow) *userFanGrpc.UserFanWithUserStatEntity) []*userFanGrpc.UserFanWithUserStatEntity {
	r := make([]*userFanGrpc.UserFanWithUserStatEntity, len(list))
	for i, item := range list {
		r[i] = f(item)
	}
	return r
}

/****************************************************************************************/
/*                            user_fanJoins entity of query                             */
/****************************************************************************************/

// ListUserFanWithUserStats  获取粉丝及其统计信息
func (s *UserAPIService) ListUserFanWithUserStats(ctx context.Context, req *userFanGrpc.ListUserFanWithUserStatsRequest) (res *userFanGrpc.ListUserFanWithUserStatsResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("user_fanImp->ListUserFanWithUserStats:%v", req)

	res = &userFanGrpc.ListUserFanWithUserStatsResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	
	q := s.dao.Q
	ts := sqlc.PBTimestampToGoTime(req.Ts)
	userID := req.UserId
	keyword := req.Keyword
	isKeywordEmpty := keyword == ""
	keywordLike := fmt.Sprintf("%%%s%%", keyword)

	total, err := q.CountUserFanWithUserStats(ctx, sqlc.CountUserFanWithUserStatsParams{
		Created:        ts,
		UserID:         userID,
		IsKeywordEmpty: isKeywordEmpty,
		Keyword:        keywordLike,
	})
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	if total == 0 {
		// 不用继续调用listfunc
		return
	}

	userFanWithUserStats, err := q.ListUserFanWithUserStats(ctx, sqlc.ListUserFanWithUserStatsParams{
		Limit:          req.Limit,
		Offset:         req.Offset,
		Created:        ts,
		UserID:         userID,
		IsKeywordEmpty: isKeywordEmpty,
		Keyword:        keywordLike,
	})
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.Total = total
	res.UserFanWithUserStats = mapUserFanWithUserStatEntityToPb(userFanWithUserStats, transformUserFanWithUserStatEntityToPb)
	return
}
